<template>

    <div class="login-wrap-out">
        <div class="login-wrap">
            <div class="ms-title">杭州龙席网络科技股份有限公司 <br> CRM客户关系管理系统</div>
            <div class="ms-login">
                <el-form label-width="0px" class="demo-ruleForm" :model="user" :rules="rules" ref="user">
                    <el-form-item prop="username">
                        <el-input v-model="user.username" placeholder="用户名"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input type="password" v-model="user.password" placeholder="密码" @keyup.enter.native="login"></el-input>
                    </el-form-item>
                    <!--<el-form-item >-->
                    <!--<el-input v-model="code"  placeholder="验证码" class="code" @keyup.enter.native="login"></el-input>-->
                    <!--</el-form-item>-->
                    <div class="login-btn">
                        <el-button type="primary" @click="login">登录</el-button>
                    </div>
                </el-form>

            </div>

        </div>

        <!--*****************操作框************-->
        <el-dialog @close="()=>{this.editDialogVisible = false}" title="修改密码" style="width: 950px;margin: auto;" :visible.sync="editDialogVisible" >
            <div class="tips" style="color: red;margin: 0 0 20px 10px;">您的密码已被重置为原始密码，为了账户安全，请及时修改密码！</div>

            <el-form  ref="changePass" :rules="passRules" label-width="100px" :model="changePass">
                <el-form-item label="旧密码：" prop='oldPass' style="margin-bottom: 20px;">
                    {{changePass.oldPass}}
                </el-form-item>
                <el-form-item label="新密码："  prop='newPass' style="margin-bottom: 20px;">
                    <el-input  style='width: 200px;'  type="password" size='small' v-model="changePass.newPass"></el-input>
                </el-form-item>
                <el-form-item label="确认密码："  prop='checkPass' style="margin-bottom: 20px;">

                    <el-input  style='width: 200px;' type="password"  size='small' v-model="changePass.checkPass"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button style='margin-left: 70px;' type="primary" @click="onSubmit('changePass')" :disabled='disabled'>确定</el-button>
                </el-form-item>
            </el-form>



        </el-dialog>
    </div>

</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios';
    import { Row, Col, Input ,FormItem ,Form, Button, Message,Dialog} from 'element-ui'
    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Input);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Button);
    Vue.use(Dialog);
    Vue.prototype.$message = Message;
    import { setToken ,browserType  } from '~/utils/auth'
    import { LOADING } from '../store/mutation-types/loading/index';
    import { mapActions,mapMutations } from 'vuex';
    import * as types from '../store/mutation-types/user_login/index';

    export default {
        layout: 'default-login',
        head(){
            return {
                title: "登录"
            }
        },
        data () {
            var validateNewPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                }else if(value==123456){
                    callback(new Error('新密码不能为初始密码'));
                } else if(value !== '' && value.length<6 ||value.length>20){
                    callback(new Error('密码长度在6到20位之间'));
                }else{
                    callback();
                }
            };
            var validateCheckPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.changePass.newPass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };

            return {
                editDialogVisible:false,

                rules: {
                    username: [
                        {required: true, message: '请输入用户名'}
                    ],
                    password: [
                        {required: true, message: '请输入密码'}
                    ]
                },
                user: {
                    username: '',
                    password: ''
                },


                disabled: false,
                changePass: {
                    oldPass: '123456',
                    newPass: '',
                    checkPass: ''
                },
                passRules: {
                    newPass: [
                        { validator: validateNewPass, trigger: 'blur' }
                    ],
                    checkPass: [
                        { validator: validateCheckPass, trigger: 'blur' }
                    ]
                },
            }
        },
        head () {
            return {
                title: 'Login'
            }
        },

        mounted(){

        },

        methods:{
            onSubmit(formName) {

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$store.dispatch('changePasswd',{"oldPasswd":this.changePass.oldPass,"newPasswd1":this.changePass.checkPass,"newPasswd2":this.changePass.newPass})
                            .then((response) => {
                                let result=response.data.code
                                if (result==0) {
                                    this.$message({
                                        message: '恭喜！修改成功，请牢记新的登录密码',
                                        type: 'success'
                                    });
                                    this.disabled=true
                                    this.$router.replace('/customer');
                                }else{
                                    this.$message.error({
                                        message: '修改密码失败,可能用户名不存在'
                                    });
                                    this.$refs[formName].resetFields();
                                }
                            })
                    }
                });
            },

            login() {

                if(!this.user.username){
                    Message.warning({
                        message: '请输入用户名'
                    });
                    return;
                } else if(!this.user.password){
                    Message.warning({
                        message: '请输入密码'
                    });
                    return;
                }

                this.$store.dispatch('getUserLogin',{'username':this.user.username , 'passwd': this.user.password })
                    .then((response) => {
                        const success = response.data.successed;
                        const code = response.data.code;
                        if(success){

                            setToken('token',response.data.data);

                            this.$store.commit(types.USER_LOGIN , {isLogin : true});
                            this.$store.commit(types.USER_TOKEN , {userToken : response.data.data.token});
                            this.$store.dispatch('getUserPersonalData')
                                .then((response) =>{
                                    const success = response.data.successed;
                                    if(success){
                                        this.$store.commit(types.USER_DATA , {userData : response.data.data});
                                        setToken('userData',JSON.stringify(response.data.data));
                                    }
                                });
                            var from = this.$route.query.from;
                            if(from && from == 'tel') {
                                this.$store.commit(types.BG_LOGIN,{ bgLogin: false});
                                window.opener.location.reload();
                                window.close();
                            }else {
                                if (this.user.password==123456) {
                                    this.editDialogVisible=true;
                                    return;
                                }
                                this.$router.replace('/customer');
                            }

                        }else{
                            Message.error({
                                message: response.data.message
                            });
                        }
                    })
                    .catch(function (error) {
                        if(error.response && error.response.status == '401'){
                            var errorMsg = error.response.data.message;
                            Message.error({
                                message: errorMsg
                            });
                        }
                    });
            },
            showExpiredTip() {
                Message.error({
                    message: '用户信息已过期,请重新登录'
                });
            }
        },
        created() {
            setToken('parentUrl','login');

            if (process.BROWSER_BUILD ) {
                var tokenExpired = window.localStorage.getItem('tokenExpired');
                if(tokenExpired == 'true') {
                    this.showExpiredTip();
                    setToken('tokenExpired', 'false');
                }
            }
        }
    }
</script>

<style lang="scss">

    .login-wrap-out{
    .login-wrap{
        position: absolute;
        left:0;
        top:0;
        z-index: 500;
        background: #324157;
        width:100%;
        height:100%;
    }
    .ms-title{
        width: 100%;
        text-align: center;
        font-size: 25px;
        color: #fff;
        position: absolute;
        left: 50%;
        top: 20%;
        -ms-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }
    .ms-login{
        position: absolute;
        left: 50%;
        top: 50%;
        width: 300px;
        border-radius: 5px;
        transform: translate(-50%, -50%);
    }
    .login-btn{
        text-align: center;
    }
    .login-btn button{
        width:100%;
        height:36px;
    }
    .el-form-item {
        margin-bottom: 30px;
    }
    .el-form-item span{
        color: #fff;
        width: 20%;
        display: inline-block;
        margin-right: 5%;
        float: left;
    }
    .el-input {
        width: 100%;
        float: left;
    }
    .el-input.code {
        width: 30%;
        float: left;
    }
    .el-form-item.is-error {
        border-color: transparent !important
    }
    }

</style>